# libs ----
library(sf)
library(geomander)
library(tidyverse)
library(redist)
library(ppmf)
library(grid)
library(patchwork)
library(wacolors)
library(here)

# helper ----
source(here('R/00_custom_functions.R'))

# data ----
state <- "DE"
path19 <- Sys.getenv('ppmf19')#"data-raw/ppmf_19.csv"
path12 <- Sys.getenv('ppmf12')#"data-raw/ppmf_12.csv"
path4 <- Sys.getenv('ppmf4')#"data-raw/ppmf_4.csv"
ppmf19 <- read_ppmf(state, path19)
ppmf12 <- read_ppmf(state, path12)
ppmf4 <- read_ppmf(state, path4)

ppmf19 <- ppmf19 %>% add_geoid() %>% agg() %>% breakdown_geoid() %>%
  rename_with(~ add_pref(.x,pref = 'v19'), starts_with(c('pop', 'vap')))
ppmf12 <- ppmf12 %>% add_geoid() %>% agg() %>% breakdown_geoid() %>%
  rename_with(~ add_pref(.x,pref = 'v12'), starts_with(c('pop', 'vap')))
ppmf4 <- ppmf4 %>% add_geoid() %>% agg() %>% breakdown_geoid() %>%
  rename_with(~ add_pref(.x,pref = 'v4'), starts_with(c('pop', 'vap')))

# comparison ----
census <- create_block_table(state = 'DE')

# all joined ----
mega <- census %>%
  left_join(ppmf12, by = 'GEOID') %>%
  left_join(ppmf4, by = 'GEOID') %>%
  left_join(ppmf19, by = "GEOID")


# add block_group back (dropped by contains('.'))
mega <- mega %>% breakdown_geoid()
# and remove duplicates
mega <- mega %>% select(-contains('.'))
# and set missing block pop/vap to 0
mega[is.na(mega)] <- 0


# from VEST 2020
prec <- st_read(here('data/DE/de_2020/de_2020.shp'))
prec <- prec %>% st_transform(st_crs(mega))

# Get Census Shapes :
sld_low <- tigris::state_legislative_districts('DE', 'lower')
sld_up <- tigris::state_legislative_districts('DE', 'upper')
cd <- tigris::congressional_districts('DE')


# Align ppmf & precincts:
block_prec_match <- geo_match(from = mega, to = prec, method = 'centroid')
prec_low_match <- geo_match(from = prec, to = sld_low, method = 'area')
prec_up_match <- geo_match(from = prec, to = sld_up, method = 'area')
prec_cd_match <- geo_match(from = prec, to = cd, method = 'area')

prec <- prec %>% mutate(
  sld_low = sld_low$SLDLST[prec_low_match],
  sld_up = sld_up$SLDUST[prec_up_match],
  cd = cd$CD116FP[prec_cd_match]
)

mega$prec <- block_prec_match
ppmf_at_prec <- ppmf_block2prec(mega, prec)


# join them together
de <- prec %>%
  mutate(prec = row_number()) %>%
  left_join(ppmf_at_prec, by = 'prec')

de$cd <- as.numeric(de$cd)
de$sld_low <- as.numeric(de$sld_low)
de$sld_up <- as.numeric(de$sld_up)
de <- de %>% mutate(row_id = row_number())

saveRDS(de, here('data/DE/de.Rds'), compress = 'xz')

